<?php
/**
 * Created by PhpStorm.
 * User: Sergey
 * Date: 14.03.14
 * Time: 11:07
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

define("BASE_DQ_PLUGIN_PATH", plugin_dir_path(__FILE__));
require_once BASE_DQ_PLUGIN_PATH . "classes/QuizDao.php";
require_once BASE_DQ_PLUGIN_PATH . "classes/GroupDao.php";
require_once BASE_DQ_PLUGIN_PATH . "classes/QuestionDao.php";
require_once BASE_DQ_PLUGIN_PATH . "classes/AnswerDao.php";
require_once BASE_DQ_PLUGIN_PATH . "classes/UserDao.php";

$quizDao = new QuizDao();
$groupDao = new GroupDao();
$questionDao = new QuestionDao();
$answerDao = new AnswerDao();
$userDao = new UserDao();

if (
    isset($_REQUEST["name"]) &&
    isset($_REQUEST["description"]) &&
    isset($_REQUEST["start_date"]) &&
    isset($_REQUEST["groups"]) && is_array($_REQUEST["groups"])
) {
    // Добавляем запись Тест
    $quiz = new Quiz();
    $quiz->id = intval($_REQUEST["id"]);
    $quiz->name = strval($_REQUEST["name"]);
    $quiz->description = strval($_REQUEST["description"]);
    $quiz->startDate = new \DateTime($_REQUEST["start_date"]);
    $quiz->endDate = new \DateTime($_REQUEST["end_date"]);
    $quiz->tutorId = wp_get_current_user()->ID;
    $quiz->groups = $_REQUEST["groups"];

    if ($quiz->id > 0) {
        $quizDao->edit($quiz);
        header("Location: " . menu_page_url("distant-quiz/admin.php", false));
    } else {
        $quiz->id = $quizDao->add($quiz);
        header(
            "Location: " .
            menu_page_url($_GET["page"], false) . "&id=" . $quiz->id
        );
    }
}

if (isset($_REQUEST["quizId"]) && intval($_REQUEST["quizId"]) > 0
    && isset($_REQUEST["action"]) && $_REQUEST["action"] == "removeQuestion"
    && isset($_REQUEST["id"]) && intval($_REQUEST["id"]) > 0
) {
    $questionDao->remove($_REQUEST["id"]);
}

$quiz = null;
if (isset($_GET["id"]) && intval($_GET["id"]) > 0) {
    $quiz = $quizDao->getById(intval($_GET["id"]));
    $quiz->groups = $quizDao->getAllGroups($quiz->id);
    $quiz->questions = $questionDao->getAllByQuizId($quiz->id);

    foreach ($quiz->questions as $question) {
        $question->answers = $answerDao->getAllByQuestionId($question->id);
    }
}

$tutor = $userDao->getById(get_current_user_id(), UserDao::ROLE_TUTOR);
?>

<? include_once BASE_DQ_PLUGIN_PATH . "header.php"; ?>

<h1>Создание нового теста</h1>

<form id="quiz-form" method="post">
    <input type="hidden" name="page" value="<?= $_REQUEST["page"] ?>"/>
    <input type="hidden" name="id" value="<?= isset($_GET["id"]) ? intval($_GET["id"]) : 0 ?>"/>

    <table class="quiz-form-table">
        <tbody>
        <tr>
            <td><label for="quiz_name">Название теста:</label></td>
            <td><input type="text"
                       name="name"
                       id="quiz_name"
                       value="<?= ($quiz) ? $quiz->name : "" ?>"/></td>
        </tr>
        <tr>
            <td><label for="quiz_description">Описание:</label></td>
            <td>
                <textarea
                    name="description"
                    id="quiz_description"><?= ($quiz) ? $quiz->description : "" ?></textarea>
            </td>
        </tr>
        <tr>
            <td><label for="quiz_start_date">Начало активности:</label></td>
            <td>
                <input type="text"
                       name="start_date"
                       id="quiz_start_date"
                       class="jquery-datepicker"
                       value="<?= ($quiz) ? $quiz->startDate->format("d.m.Y") : "" ?>"/>
            </td>
        </tr>
        <tr>
            <td><label for="quiz_end_date">Конец активности:</label></td>
            <td>
                <input type="text"
                       name="end_date"
                       id="quiz_end_date"
                       class="jquery-datepicker"
                       value="<?= ($quiz) ? $quiz->endDate->format("d.m.Y") : "" ?>"/>
            </td>
        </tr>
        <tr>
            <td><label for="quiz_groups">Группы:</label></td>
            <td>
                <? if (count($tutor->groups) > 0) { ?>
                    <select id="quiz_groups"
                            name="groups[]" size="10" multiple
                            title="Удерживайте Ctrl и выделите группы">
                        <? foreach ($tutor->groups as $groupId) { ?>
                            <? $group = $groupDao->getById($groupId); ?>
                            <option value="<?= $group->id ?>"
                                <?= ($quiz && $group && in_array($group->id, $quiz->groups)) ? "selected" : "" ?>>
                                <?= $group->name ?>
                            </option>
                        <? } ?>
                    </select>
                <? } else { ?>
                    <span class="error">
                        У вас нет прав на добавление тестов, так как у вас нет доступных групп.
                        Обратитесь к администратору.
                    </span>
                <? } ?>
            </td>
        </tr>
        </tbody>
    </table>
    <br>

    <input type="submit" value="Сохранить изменения"/><br><br>

    <? if ($quiz) { ?>
        <a href="<?=
        menu_page_url("distant-quiz/question-form.php", false) .
        "&quizId=" . $quiz->id;
        ?>" class="jquery-button">
            + Добавить вопрос
        </a>
    <? } ?>
    <br>
    <br>

    <table class="content-table">
        <thead>
        <tr>
            <th>#</th>
            <th>Текст вопроса</th>
            <th>Ответы, (правильные отмечены знаком "+")</th>
            <th>Операции</th>
        </tr>
        </thead>
        <tbody>
        <? if ($quiz && $quiz->questions) { ?>
            <? foreach ($quiz->questions as $question) { ?>
                <tr>
                    <td><?= $question->id ?></td>
                    <td><?= $question->content ?></td>
                    <td>
                        <table>
                            <? if ($question) { ?>
                                <? foreach ($question->answers as $answer) { ?>
                                    <tr>
                                        <td><?= ($answer->isCorrect) ? "+" : "" ?></td>
                                        <td><?= $answer->content ?></td>
                                    </tr>
                                <? } ?>
                            <? } ?>
                        </table>
                    </td>
                    <td>
                        <a href="<?=
                        menu_page_url("distant-quiz/question-form.php", false) .
                        "&quizId=" . $quiz->id .
                        "&id=" . $question->id;?>"
                           class="jquery-button">
                            Редактировать</a>
                        <hr>

                        <a href="<?=
                        menu_page_url($_GET["page"], false) .
                        "&quizId=" . $quiz->id .
                        "&action=removeQuestion" .
                        "&id=" . $question->id;?>"
                           class="jquery-button">
                            Удалить</a>
                    </td>
                </tr>
            <? } ?>
        <? } ?>
        </tbody>
    </table>
    <br>
    <input type="submit" value="Сохранить изменения"/>

</form>